/*
 * Copyright (c) 2022  by Junzhao
 * THIS FILE IS PART OF JAVASE Song Huongkang PROJECT
 * All Rights Reserved.
 */

package 实现Callable接口;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @description  实现多线程的方式三
 *      实现Callable接口
 *      重写call（）方法
 *      创建其实现类实例
 *      调用FutureTask类（间接实现了Runnable接口）
 *      利用FutureTask的实例调用各种方法如 get（）获取call方法的返回值
 *      用FutureTask类的实例构造Thread对象 调用start()方法
 *
 *
 * @author 俊昭
 * @date 2022/4/13
*/
public class CallableTest {
    public static void main(String[] args) {
        NumThread nt1 =new NumThread();
        FutureTask ft1 =new FutureTask(nt1);
        Thread t1 = new Thread(ft1);
        t1.start();

        try {
            Object sum = ft1.get();
            System.out.println("总和为"+sum);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
class NumThread implements Callable{

    @Override
    public Object call() throws Exception {
        Integer sum=0;
        for (int i = 0;i<100;i++) {
            if (i %2==0){
                System.out.println(i);
                sum+=i;
            }
        }
        return sum;
    }
}